from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from Util.SQL import *
from Util.Return import get_image
import time


@csrf_exempt
def index(request):
    if request.method == "GET":
        position1 = request.session.get('position1', 0)
        context = {'position1': position1}  # 未进行查询，position1返回默认值
        return render(request, 'index.html', context)
    # data_list = request.session.get('data_list', [])  # 读取缓存
    position1 = request.POST.get('position1', '0')  # 读取输入位置
    current_time = datetime.now().strftime('%Y-%m-%d')
    startdate = request.POST.get('startdate', '0')  # 读取输入开始时间
    enddate = request.POST.get('enddate', '0')  # 读取输入结束时间
    if len(startdate) == 0 & len(enddate) == 0:                     #处理用户未输入完全日期的情况
        startdate = current_time
        enddate = current_time
    elif len(startdate) == 0:
        startdate = enddate
    elif len(enddate) == 0:
        enddate = startdate
    datatype = request.POST.get('datatype', '0')  # 原始数据/处理后数据
    date = [startdate, enddate]

    sc, boundary = get_location(position1, True)  # 获取bbox值
    print(sc)
    if sc == -1:  # 获取不到bbox值
        sc, boundary = get_location(position1, False)  # 获取经纬度
        # print(sc)
        if sc != -1:  # 获取到经纬度
            ori_string = "\
            SELECT scene_id,date,bbox,dataset,cbox,type,satellite,available,address,json,a,b,c,d\
                FROM (\
                    SELECT \
                        scene_id, date, bbox, dataset, cbox, type, satellite, available,address, json,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 2), ', ', -1) AS DECIMAL(10, 5)) AS b,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 3), ', ', -1) AS DECIMAL(10, 5)) AS c,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                    FROM data\
                ) AS temp\
            WHERE \
                a < @ \
                AND b < # \
                AND c > @ \
                AND d > #\
                AND available=1\
                AND date BETWEEN '&' AND '~';"
            sql_string = ori_string.replace("@", str(sc['lng'])).replace("#", str(sc['lat'])).replace("&", str(date[0])).replace("~", str(date[1]))
            result = select(sql_string)  # 获取符合该经纬度的数据
        else:
            result = []  # 未获取到经纬度，赋初值
    else:
        # start = time.perf_counter()
        ori_string = "\
            SELECT scene_id,date,bbox,dataset,cbox,type,satellite,available,address,json,a,b,c,d\
                FROM (\
                    SELECT \
                        scene_id,date,bbox,dataset,cbox,type,satellite,available,address,json,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 2), ', ', -1) AS DECIMAL(10, 5)) AS b,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 3), ', ', -1) AS DECIMAL(10, 5)) AS c,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                    FROM data\
                ) AS temp\
                WHERE \
                    (c>@ AND a<$) AND (d># AND b<%) AND available=1\
                    AND date BETWEEN '&' AND '~';"
        sql_string = ori_string.replace("@", str(sc[0])).replace("#", str(sc[1])).replace("$", str(sc[2])).replace("%",str(sc[3])).replace("&", str(date[0])).replace("~", str(date[1]))
        result = select(sql_string)  # 获取符合该bbox的数据
        # end = time.perf_counter()
        # print(end-start)
        # print(result)
    if result is None:
        context = {'scenes': -1, 'sc': sc, 'boundary': boundary}  # bbox和经纬度都找不到
    else:
        imgs = []
        for items in result:  # 获取所有符合的图片
            img = get_image("quick_look", items["scene_id"])
            imgs.append(img)
        if isinstance(sc, tuple):
            jud = 1
        else:
            jud = 0
        context = {'scenes': result, 'sc': sc, 'jud': jud, 'boundary': boundary, 'imgs': imgs}
    return JsonResponse(context)


def findimg(request, nid, datatype):
    img = get_image(int(datatype), nid)
    context = {'img': img}
    return JsonResponse(context)
